﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Reflection;

using TSFileOutput.Core;


namespace TSFileOutput
{
    public enum TypeOfFile { CSV, ColumnLengthOriented }

    public class FileGenerator
    {
        string OutputDirectory = "", ArchieveDirectory = "";
        protected bool EmailActvie = false;
        protected string SMTP = string.Empty;
        public ArrayList LoggedMessages = new ArrayList();

        public FileGenerator(string output_path, string archieve_path, string DBConnectionString, TypeOfDatabase DatabaseType, bool Email_Active, string SMTP)
        {
            string NewFolderName = DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Year + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute;
            this.OutputDirectory = output_path;
            this.ArchieveDirectory = archieve_path + "\\" + NewFolderName + "\\";
            this.EmailActvie = Email_Active;
            this.SMTP = SMTP;

            if (!Directory.Exists(this.ArchieveDirectory))
            {
                Directory.CreateDirectory(this.ArchieveDirectory);
            }

            Directory.CreateDirectory(this.OutputDirectory);
        }

        public bool GenerateMyPending4Approval(TypeOfFile OutputType)
        {
            bool smooth = true;
            this.LoggedMessages = new ArrayList();

            StringBuilder ContentBuilder = new StringBuilder();
            StringBuilder LineItemBuilder = new StringBuilder();

            using (TimeEntryTransactionDataOutputManager CurManager = new TimeEntryTransactionDataOutputManager())
            {
                using (ProjectManager CurPM = new ProjectManager())
                {
                    TSProjectManagers PMCollection = CurPM.GetPMs();

                    if (PMCollection != null)
                    {
                        LoggedMessages.Add("*** TIMESHEET EXTRACT ***");

                        for (int z = 0; z < PMCollection.Count; z++)
                        {
                            //if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
                            {
                                // found out is today!
                                ContentBuilder = new StringBuilder();
                                ArrayList ResultList = CurManager.GenerateFileContent(PMCollection[z].Name);
                                EmailGenerator emailGenerator = new EmailGenerator(new Uri(Path.GetDirectoryName(Assembly.GetAssembly(typeof(FileGenerator)).CodeBase) + "\\Pending4Approval.htm").LocalPath);

                                try
                                {
                                    if (ResultList != null)
                                    {
                                        if (ResultList.Count > 1)
                                        {
                                            #region Generate CSV

                                            ContentBuilder = new StringBuilder();
                                            string FileName = "TS-Pending4Approval-" + PMCollection[z].Name + ".csv";
                                            string ActualPath = this.OutputDirectory + "\\" + FileName;

                                            for (int x = 0; x < ResultList.Count; x++)
                                            {
                                                string[] ResultData = (string[])ResultList[x];
                                                LineItemBuilder = new StringBuilder();

                                                for (int y = 0; y < CurManager.DataColumns.Count; y++)
                                                {
                                                    LineItemBuilder.Append(ResultData[CurManager.DataColumns[y].ColumnIndex] + ",");
                                                }

                                                ContentBuilder.AppendLine(LineItemBuilder.ToString());
                                            }

                                            // create file now
                                            FileCreate(ActualPath, Encoding.ASCII.GetBytes(ContentBuilder.ToString()));
                                            FileCreate(this.ArchieveDirectory + FileName, Encoding.ASCII.GetBytes(ContentBuilder.ToString()));
                                            LoggedMessages.Add("File Created: " + FileName);
                                            #endregion

                                            #region Send Email to PM
                                            // send email now.
                                            string contents = emailGenerator.GeneratePending4Aproval(PMCollection[z].Name, TSConfigurator.FromDate, TSConfigurator.ToDate);
                                            if (this.EmailActvie) SendEmail(contents, emailGenerator.MailTitle, PMCollection[z].Email, CreateAttachment(ActualPath));
                                            // hard code 4 test
                                            //if (this.EmailActvie) SendEmail(contents, emailGenerator.MailTitle, "thangnv@abeo-electra.com", CreateAttachment(ActualPath));

                                            LoggedMessages.Add("Sent e-mail to " + PMCollection[z].Name + " by e-mail: " + PMCollection[z].Email);
                                            #endregion
                                        }
                                        else
                                        {
                                            LoggedMessages.Add("No File for " + PMCollection[z].Name + " PM. ");
                                        }
                                    }
                                    else
                                    {
                                        LoggedMessages.Add("File Failed for " + PMCollection[z].Name + " : " + CurManager.ErrMsg);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LoggedMessages.Add("File Failed for " + PMCollection[z].Name + " : Exception : " + ex.Message);
                                }
                            }
                        }   // for z
                    }   // (CompanyCollection != null)
                }   // CompanyManagerr
            }   // ClaimTransactionDataOutputManager

            return smooth;
        }

        private bool FileCreate(string path, byte[] FileContent)
        {
            try
            {
                FileStream fs = File.Create(path);
                fs.Write(FileContent, 0, FileContent.Length);
                fs.Flush();
                fs.Close();
                fs = null;
            }
            catch (Exception ex)
            {
                //this.ShowErrorMessage("Create supporting document error: " + ex.Message);
                return false;
            }
            return true;
        }

        #region Send Email
        public void SendEmail(string MailContent, string title, string EmailToAddress, Attachment item)
        {
            try
            {
                string EmailToAdd = EmailToAddress;
                string EmailFromAdd = TSConfigurator.EmailFromAdd;
                string EmailFromName = TSConfigurator.EmailFromName;

                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(new MailAddress(EmailToAdd));
                mailMessage.From = new MailAddress(EmailFromAdd, EmailFromName);
                mailMessage.Subject = title;
                mailMessage.Priority = MailPriority.High;
                mailMessage.BodyEncoding = Encoding.UTF8;
                mailMessage.IsBodyHtml = true;
                mailMessage.Body = MailContent;
                mailMessage.Attachments.Add(item);
                SmtpClient smtp = new SmtpClient(this.SMTP);

                //for gmail
                smtp.EnableSsl = true;
                smtp.UseDefaultCredentials = false;
                //smtp.Credentials = new NetworkCredential(TSConfigurator.EmailFromAdd.Split('@')[0], TSConfigurator.EmailFromPass);
                smtp.Credentials = new NetworkCredential(TSConfigurator.EmailFromAdd, TSConfigurator.EmailFromPass);
                smtp.Host = this.SMTP;
                smtp.Port = 587;
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

                smtp.Send(mailMessage);
            }
            catch (Exception ex)
            {
                LoggedMessages.Add("[SendEmail (" + title + ")] : Exception : " + ex.Message);
                LoggedMessages.Add("[SendEmail (" + title + ")] : Exception : " + ex.ToString());
            }
        }
        #endregion

        private Attachment CreateAttachment(string fullFileName)
        {
            try
            {
                // Create  the file attachment for this e-mail message.
                Attachment data = new Attachment(fullFileName, MediaTypeNames.Application.Octet);
                // Add time stamp information for the file.
                ContentDisposition disposition = data.ContentDisposition;
                disposition.CreationDate = System.IO.File.GetCreationTime(fullFileName);
                disposition.ModificationDate = System.IO.File.GetLastWriteTime(fullFileName);
                disposition.ReadDate = System.IO.File.GetLastAccessTime(fullFileName);
                return data;
            }
            catch (Exception ex)
            {
                return null;
            } 
        }

    }
}
